package com.kfzx.www.imagetest;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private ImageView imageView;
    private Button takeAPhoto, selectFromAlbum;

    //图片的uri
    private Uri imageUri = null;

    private EditText editText;
    private int number=100;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initPermissions();


        initView();
    }

    private void initPermissions() {
        List<String> permissions = new ArrayList<>();

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.CAMERA);
        }
        if (permissions.size() > 0) {
            String[] permissionStrings = new String[permissions.size()];
            permissions.toArray(permissionStrings);
            ActivityCompat.requestPermissions(MainActivity.this, permissionStrings, 100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 100:
                if (grantResults.length > 0) {
                    for (int i : grantResults) {
                        if (i != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(MainActivity.this, "权限不足，请允许权限", Toast.LENGTH_LONG);
                            finish();
                        }
                    }
                } else {

                }
                break;
            default:
                break;
        }

    }

    private void initView() {
        imageView = (ImageView) findViewById(R.id.image);

        editText = (EditText) findViewById(R.id.edit_text);

        takeAPhoto = (Button) findViewById(R.id.take_a_photo);
        takeAPhoto.setOnClickListener(this);

        selectFromAlbum = (Button) findViewById(R.id.select_from_album);
        selectFromAlbum.setOnClickListener(this);

    }


    @Override
    public void onClick(View view) {
        String inputString= editText.getText().toString();
        if (TextUtils.isEmpty(inputString)){
            number = 100;
        }else {
            number= Integer.parseInt(inputString);
        }

        switch (view.getId()) {
            case R.id.take_a_photo:
                takePhoto();
                break;
            case R.id.select_from_album:
                selectAlbum();
                break;
        }
    }

    private void takePhoto() {

        //将照片放在该应用的缓冲文件夹下，命名为output_image.jpg
        File outputImage = new File(MainActivity.this.getExternalCacheDir(), "output_image.jpg");
        //getExternalCacheDir可以得到应用关联目录 可以避免6.0运行时权限的处理
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            Log.e(TAG, "文件出错" + e);
        }
        // 判断手机系统是否小于7.0 获取照片的URI
        // 应用关联目录 可以避免6.0运行时权限的处理
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(MainActivity.this,
                    "com.kfzx.www.imagetest.fileprovider", outputImage);
        } else {
            imageUri = Uri.fromFile(outputImage);
        }

        //启动系统相机程序
        Intent intent1 = new Intent("android.media.action.IMAGE_CAPTURE");
        intent1.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent1, 1);

    }

    private void selectAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, 2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode==RESULT_OK){
                    //图片压缩4倍后再显示
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 4;
                    Bitmap srcBitmap = null;
                    try {
                        srcBitmap = BitmapFactory.decodeStream(
                                getContentResolver().openInputStream(imageUri), null, options);
                        Base64Utils. Bitmap2Base64AndSaveFile(srcBitmap,number);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    imageView.setImageBitmap(srcBitmap);
                }
                break;
            case 2:

                if (resultCode == RESULT_OK) {
                    //判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4及以上系统执行这个方法处理图片
                        handleImageOnKitKat(data);
                    }
                }

                break;
            default:
                break;
        }
    }

    /**
     * 处理4.4以上的系统
     *
     * @param data
     */
//    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(MainActivity.this, uri)) {
            // 如果是document类型的uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.
                        parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的uri 则使用普通方法处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的uri 直接获取路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath);//根据图片路径显示图片

    }

    /**
     * 获取图片的路径，
     *
     * @param uri
     * @param selection
     * @return
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过uri和selection来获取真实的图片路径
        Cursor cursor = MainActivity.this.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    /**
     * 显示选中的图片，将图片放到PhotoPreviewActivity
     *
     * @param imagePath
     */
    private void displayImage(String imagePath) {

//        Intent intent2 = new Intent(getContext(), PhotoPreviewActivity.class);
//        intent2.putExtra("choice", CHOOSE_PHOTO);
//        intent2.putExtra("image", imagePath);
//        startActivity(intent2);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 4;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
        imageView.setImageBitmap(bitmap);

       Base64Utils. Bitmap2Base64AndSaveFile(bitmap,number);
    }
}
